package admin

import (
	"github.com/gin-gonic/gin"
	"go-ecommerce/internal/service"
	"go-ecommerce/internal/utils"
	"go-ecommerce/internal/validate"
	"net/http"
)

func LoginHandle(c *gin.Context) {
	var req validate.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, 4001, "参数错误"+err.Error())
		return
	}
	if utils.VerifyCaptcha(req.CaptchaID, req.Captcha) != true {
		utils.Error(c, 1, "验证码错误")
		return
	}

	user, err := service.Login(req.Username, req.Password)
	if err != nil {
		utils.Error(c, 4001, "登录失败"+err.Error())
		return
	}
	// 生成 token
	token, err := utils.GenerateToken(user.ID, user.Username)

	if err != nil {
		utils.Error(c, 1005, "生成Token失败："+err.Error())
		return
	}
	data := make(map[string]string)
	data["token"] = token
	utils.Success(c, "ok", data)

}

// GetCaptcha 生成验证码图片并返回验证码ID和base64图片
func GetCaptcha(c *gin.Context) {
	_, err := utils.GenerateCaptchaImage(c.Writer, c.Request)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "验证码生成失败",
		})
		return
	}

}
